Page({
  data: {
    id: null,
    detail: null,
    trackingSteps: [],
    loading: false,
    error: null
  },

  onLoad(query) {
    console.log('exchange-detail onLoad - 接收到的参数:', query);
    
    const { orderId, id } = query;
    const orderIdToUse = orderId || id;
    
    console.log('使用的订单ID:', orderIdToUse);
    
    if (!orderIdToUse) {
      console.error('订单ID参数缺失');
      this.setData({
        error: '订单ID参数缺失，请返回重新操作'
      });
      return;
    }
    
    this.setData({ 
      id: orderIdToUse,
      loading: true,
      error: null
    });
    this.loadExchangeDetail(orderIdToUse);
  },

  onUnload() {
    // 页面卸载时，如果状态已更新，设置全局刷新标志
    if (this.data.detail && this.data.detail.status === 'completed') {
      try {
        const app = getApp();
        if (app && app.globalData) {
          app.globalData.needRefreshHistory = true;
          console.log('页面卸载时设置全局刷新标志');
        }
      } catch (error) {
        console.error('设置全局刷新标志失败:', error);
      }
    }
  },

  // 加载兑换详情
  loadExchangeDetail(id) {
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    this.setData({ loading: true, error: null });

    // 调用后端接口获取兑换订单详情（多表联查）
    wx.request({
      url: 'http://localhost:8080/point/order/detail/' + id,
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        console.log('兑换详情API返回数据:', res.data);
        
        if (res.data.code === 200) {
          const orderData = res.data.data;
          // 转换数据格式，根据实际API返回的字段名和嵌套结构
          const detail = {
            id: orderData.id,
            title: orderData.goodsName || (orderData.mallGoods ? orderData.mallGoods.name : ''),
            imageUrl: this.getFullImageUrl(orderData.mallGoods ? orderData.mallGoods.coverImg : ''),
            points: orderData.point || 0,
            exchangeTime: orderData.createTime || '',
            status: this.getStatusText(orderData.status),
            orderNumber: orderData.orderSn || '',
            trackingNumber: orderData.logistics ? orderData.logistics.expressNo : '',
            expressCompany: orderData.logistics ? orderData.logistics.expressCompany : '',
            recipient: orderData.userAddress ? orderData.userAddress.consignee : '',
            phone: orderData.userAddress ? orderData.userAddress.phone : '',
            address: orderData.userAddress ? orderData.userAddress.address : '',
            deliveryTime: this.getDeliveryTime(orderData),
            validDays: orderData.mallGoods ? orderData.mallGoods.validityDays : 0,
            exchangeCount: orderData.mallGoods ? orderData.mallGoods.exchangeCount : 0,
            description: orderData.mallGoods ? orderData.mallGoods.desc : '',
            originalPrice: orderData.mallGoods ? orderData.mallGoods.originalPrice : 0,
            stock: orderData.mallGoods ? orderData.mallGoods.stock : 0,
            sales: orderData.mallGoods ? orderData.mallGoods.sales : 0,
            specifications: this.generateSpecifications(orderData),
            logisticsId: orderData.logistics ? orderData.logistics.id : null
          };

          console.log('转换后的兑换详情:', detail);
          console.log('物流ID:', detail.logisticsId);

          // 生成物流跟踪步骤
          const trackingSteps = this.generateTrackingSteps(detail);
          console.log('生成的物流跟踪步骤:', trackingSteps);
          
          this.setData({
            detail: detail,
            trackingSteps: trackingSteps,
            loading: false,
            error: null
          });
        } else {
          this.setData({
            loading: false,
            error: res.data.msg || '获取兑换详情失败'
          });
          wx.showToast({
            title: res.data.msg || '获取兑换详情失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取兑换详情失败', err);
        this.setData({
          loading: false,
          error: '网络请求失败，请检查网络连接'
        });
        wx.showToast({
          title: '获取兑换详情失败',
          icon: 'none'
        });
      }
    });
  },

  // 获取状态文本
  getStatusText(status) {
    switch (status) {
      case 0:
        return 'pending';
      case 1:
        return 'shipped';
      case 2:
        return 'completed';
      default:
        return 'pending';
    }
  },

  // 获取完整的图片URL
  getFullImageUrl(imagePath) {
    if (!imagePath) return '';
    if (imagePath.startsWith('http')) return imagePath;
    return 'https://gzq123.oss-cn-beijing.aliyuncs.com/' + imagePath;
  },

  // 获取发货时间
  getDeliveryTime(orderData) {
    // 如果订单状态是已发货，使用更新时间作为发货时间
    if (orderData.status === 1 && orderData.updateTime) {
      return orderData.updateTime;
    }
    // 如果订单状态是已完成，也使用更新时间
    if (orderData.status === 2 && orderData.updateTime) {
      return orderData.updateTime;
    }
    return null;
  },

  // 生成规格信息
  generateSpecifications(orderData) {
    const specs = [];
    
    // 处理specifications字段
    if (orderData.mallGoods && orderData.mallGoods.specifications && Array.isArray(orderData.mallGoods.specifications)) {
      orderData.mallGoods.specifications.forEach(spec => {
        if (spec && typeof spec === 'object') {
          if (spec.name && spec.value) {
            specs.push(`${spec.name}: ${spec.value}`);
          } else if (spec.description) {
            specs.push(spec.description);
          }
        } else if (typeof spec === 'string') {
          specs.push(spec);
        }
      });
    }
    
    // 添加基础商品信息作为规格
    if (orderData.mallGoods) {
      if (orderData.mallGoods.stock > 0) {
        specs.push(`库存: ${orderData.mallGoods.stock}件`);
      }
      if (orderData.mallGoods.validityDays > 0) {
        specs.push(`有效期: ${orderData.mallGoods.validityDays}天`);
      }
      if (orderData.mallGoods.sales > 0) {
        specs.push(`已售: ${orderData.mallGoods.sales}件`);
      }
      if (orderData.mallGoods.exchangeCount > 0) {
        specs.push(`已兑换: ${orderData.mallGoods.exchangeCount}次`);
      }
      if (orderData.mallGoods.originalPrice > 0) {
        specs.push(`原价: ¥${orderData.mallGoods.originalPrice}`);
      }
    }
    
    return specs;
  },

  // 生成物流跟踪步骤
  generateTrackingSteps(detail) {
    const steps = [];
    const exchangeTime = detail.exchangeTime;
    const deliveryTime = detail.deliveryTime;
    
    // 第一步：已兑换
    steps.push({
      time: exchangeTime,
      status: '已兑换',
      description: '积分兑换成功，订单已生成'
    });
    
    if (detail.status === 'completed') {
      // 已完成状态：显示完整的物流流程
      if (detail.trackingNumber && detail.expressCompany) {
        // 有物流信息的情况
        steps.push({
          time: exchangeTime,
          status: '处理中',
          description: '商品正在准备中，请耐心等待'
        });
        
        steps.push({
          time: deliveryTime || exchangeTime,
          status: '已发货',
          description: `商品已由${detail.expressCompany}发出，快递单号：${detail.trackingNumber}`
        });
        
        steps.push({
          time: deliveryTime || exchangeTime,
          status: '运输中',
          description: `商品正在由${detail.expressCompany}配送中`
        });
        
        steps.push({
          time: deliveryTime || exchangeTime,
          status: '已完成',
          description: '商品已送达并签收'
        });
      } else {
        // 无物流信息的情况（可能是虚拟商品）
        steps.push({
          time: exchangeTime,
          status: '处理中',
          description: '商品正在准备中，请耐心等待'
        });
        
        steps.push({
          time: deliveryTime || exchangeTime,
          status: '已完成',
          description: '商品已发放到账户'
        });
      }
    } else if (detail.status === 'shipped') {
      // 已发货状态
      steps.push({
        time: exchangeTime,
        status: '处理中',
        description: '商品正在准备中，请耐心等待'
      });
      
      if (detail.trackingNumber && detail.expressCompany) {
        steps.push({
          time: deliveryTime || exchangeTime,
          status: '已发货',
          description: `商品已由${detail.expressCompany}发出，快递单号：${detail.trackingNumber}`
        });
        
        steps.push({
          time: deliveryTime || exchangeTime,
          status: '运输中',
          description: `商品正在由${detail.expressCompany}配送中`
        });
      } else {
        steps.push({
          time: deliveryTime || exchangeTime,
          status: '已发货',
          description: '商品已发出，请等待配送'
        });
      }
    } else {
      // 处理中状态
      steps.push({
        time: exchangeTime,
        status: '处理中',
        description: '商品正在准备中，请耐心等待'
      });
    }
    
    return steps;
  },

  // 复制订单号
  copyOrderNumber() {
    const { detail } = this.data;
    if (detail.orderNumber) {
      wx.setClipboardData({
        data: detail.orderNumber,
        success: () => {
          wx.showToast({
            title: '订单号已复制',
            icon: 'success'
          });
        }
      });
    } else {
      wx.showToast({
        title: '订单号不存在',
        icon: 'none'
      });
    }
  },

  // 复制快递单号
  copyTrackingNumber() {
    const { detail } = this.data;
    if (detail.trackingNumber && detail.trackingNumber.trim()) {
      wx.setClipboardData({
        data: detail.trackingNumber,
        success: () => {
          wx.showToast({
            title: '快递单号已复制',
            icon: 'success'
          });
        }
      });
    } else {
      wx.showToast({
        title: '暂无快递单号',
        icon: 'none'
      });
    }
  },

  // 联系客服
  contactService() {
    wx.showModal({
      title: '联系客服',
      content: '客服电话：400-123-4567\n工作时间：9:00-18:00',
      showCancel: false
    });
  },

  // 预览图片
  onPreviewImage() {
    const { detail } = this.data;
    if (detail.imageUrl) {
      wx.previewImage({
        current: detail.imageUrl,
        urls: [detail.imageUrl]
      });
    } else {
      wx.showToast({
        title: '暂无商品图片',
        icon: 'none'
      });
    }
  },

  // 重试加载
  retryLoad() {
    if (this.data.id) {
      this.loadExchangeDetail(this.data.id);
    }
  },

  // 确认收货
  confirmReceipt() {
    console.log('确认收货，物流ID:', this.data.detail.logisticsId);
    
    if (!this.data.detail.logisticsId) {
      wx.showToast({
        title: '物流信息不存在',
        icon: 'none'
      });
      return;
    }
    
    wx.showModal({
      title: '确认收货',
      content: '确认已收到商品吗？',
      success: (res) => {
        if (res.confirm) {
          this.submitReceipt();
        }
      }
    });
  },

  // 提交收货
  submitReceipt() {
    wx.showLoading({
      title: '提交中...'
    });

    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    // 调用后端接口确认收货
    wx.request({
      url: 'http://localhost:8080/point/logistics/received/' + this.data.detail.logisticsId,
      method: 'PUT',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        wx.hideLoading();
        console.log('收货API返回数据:', res.data);
        
        if (res.data.code === 200) {
          wx.showToast({
            title: '收货成功',
            icon: 'success'
          });
          
          // 更新页面状态
          this.setData({
            'detail.status': 'completed'
          });
          
          // 更新物流跟踪步骤
          const updatedTrackingSteps = this.generateTrackingSteps({
            ...this.data.detail,
            status: 'completed'
          });
          this.setData({
            trackingSteps: updatedTrackingSteps
          });
          
          // 通知exchange-history页面更新状态
          this.notifyHistoryPageUpdate();
          
          // 刷新页面数据
          this.loadExchangeDetail(this.data.id);
        } else {
          wx.showToast({
            title: res.data.msg || '收货失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('收货请求失败:', err);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 通知exchange-history页面更新状态
  notifyHistoryPageUpdate() {
    try {
      // 方式1：通过页面栈通知
      const pages = getCurrentPages();
      if (pages.length > 1) {
        const prevPage = pages[pages.length - 2];
        if (prevPage && prevPage.route === 'my/pages/exchange-history/exchange-history') {
          console.log('通知exchange-history页面更新状态');
          prevPage.updateExchangeHistory();
        }
      }
      
      // 方式2：通过全局事件总线通知（如果有的话）
      if (typeof getApp !== 'undefined') {
        const app = getApp();
        if (app && app.globalData) {
          app.globalData.needRefreshHistory = true;
          console.log('设置全局刷新标志');
        }
      }
    } catch (error) {
      console.error('通知页面更新失败:', error);
    }
  }
}); 